package com.happy.config.shiro;

import com.alibaba.fastjson.JSONObject;
import com.happy.service.LoginService;
import com.happy.util.constants.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;


/**
 * @Auther: lifeng
 * @Date: 2018/6/26 15:43
 * @Description:自定义realm
 */
public class UserRealm extends AuthorizingRealm {
    private Logger log = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    LoginService loginService;
    /***
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Session session =  SecurityUtils.getSubject().getSession();
        //查询用户的权限
        JSONObject permission = (JSONObject) session.getAttribute(Constants.SESSION_USER_PERMISSION);
        log.info("permission的值为:" + permission);
        log.info("本用户权限为:" + permission.get("permissionList"));
        //为当前用户设置角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addObjectPermissions((Collection<Permission>) permission.get("permissionList"));
        return null;
    }

    /***
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //获取用户名
        String username = (String) authenticationToken.getPrincipal();
        //获取密码
        String password = new String ((char[])authenticationToken.getCredentials());
        JSONObject user = loginService.getUser(username,password);
        if(user==null){
            throw new UnknownAccountException();
        }
        //认证
        SimpleAuthenticationInfo authenticationInfo  = new SimpleAuthenticationInfo(
                user.get("username"),
                user.get("password"),
                //ByteSource.Util.bytes("salt"), salt=username+salt,采用明文访问时，不需要此句
                getName()
        );
        //session中不需要保存密码
        user.remove("password");
        //将用户信息放入session中
        SecurityUtils.getSubject().getSession().setAttribute(Constants.SESSION_USER_INFO,user);
        return authenticationInfo;
    }
}
